package no.ntnu.fp.handlers;

import java.io.IOException;
import java.util.List;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.MeetingUpdatedMessage;
import no.ntnu.fp.messages.impl.UpdateMeetingMessage;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.model.Notice.NoticeType;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.services.MeetingService;
import no.ntnu.fp.services.NoticeService;
import no.ntnu.fp.utils.Participant;

public class UpdateMeetingHandler implements Handler {
	private final MeetingService meetingService;
	private final NoticeService noticeService;
	
	public UpdateMeetingHandler(MeetingService meetingService,
			NoticeService noticeService) {
		this.meetingService = meetingService;
		this.noticeService = noticeService;
	}

	@Override
	public void handleMessage(Message message) {
		UpdateMeetingMessage updateMeetingMessage 
											= (UpdateMeetingMessage) message;
		
		Meeting meeting = updateMeetingMessage.getMeeting();
		
		List<Participant> oldParticipants = meetingService.updateMeeting(meeting);
		
		//If an employee is deleted, he needs to know! His meeting must be deleted
		
		noticeService.notifyParticipants(meeting, NoticeType.ChangedMeeting,
														meeting.getEmployee());
		noticeService.sendDeletionNotice(oldParticipants, meeting);
		Message reply = new MeetingUpdatedMessage(meeting);
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			throw new NetworkException("Could not send meeting update " +
								"acknowledgement for meeting " + meeting, e);
		}
	}

}
